Enums

Without Associated Type

  • Creation :

    enum CompassPoint {
        case north
        case south
        case east
        case west
    }
    
    enum Planet {
        case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
    }
    
  • Access :

    var directionToHead = CompassPoint.west
    
    • Once directionToHead  is declared as a CompassPoint , you can set it to a different CompassPoint  value using a shorter dot syntax:

      directionToHead = .east
      
      directionToHead = .south
      switch directionToHead {
      case .north:
          print("Lots of planets have a north")
      case .south:
          print("Watch out for penguins")
      case .east:
          print("Where the sun rises")
      case .west:
          print("Where the skies are blue")
      }
      

With Associated Type

  • Creation :

    enum Barcode {
        case upc(Int, Int, Int, Int)
        case qrCode(String)
    }
    
    • This definition doesn’t provide any actual Int  or String  values — it just defines the type  of associated values that constants and variables can store when they’re equal to Barcode.upc  or Barcode.qrCode .

    var productBarcode = Barcode.upc(8, 85909, 51226, 3)
    
    productBarcode = .qrCode("ABCDEFGHIJKLMNOP")
    
  • Access :

    switch productBarcode {
    case .upc(let numberSystem, let manufacturer, let product, let check):
        print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
    case .qrCode(let productCode):
        print("QR code: \(productCode).")
    }
    // Prints "QR code: ABCDEFGHIJKLMNOP."
    
    • If all of the associated values for an enumeration case are extracted as constants, or if all are extracted as variables, you can place a single let  or var  annotation before the case name, for brevity:

      switch productBarcode {
      case let .upc(numberSystem, manufacturer, product, check):
          print("UPC : \(numberSystem), \(manufacturer), \(product), \(check).")
      case let .qrCode(productCode):
          print("QR code: \(productCode).")
      }
      // Prints "QR code: ABCDEFGHIJKLMNOP."
      

Iterating

  • Swift exposes a collection of all the cases as an allCases  property of the enumeration type if you write CaseIterable  after the enumeration’s name.

enum Beverage: CaseIterable {
    case coffee, tea, juice
}

let numberOfChoices = Beverage.allCases.count
print("\(numberOfChoices) beverages available")
// Prints "3 beverages available"


for beverage in Beverage.allCases {
    print(beverage)
}
// coffee
// tea
// juice

Default Value

  • Swift enumeration cases don’t have an integer value set by default.

  • In the CompassPoint  example above, north , south , east  and west  don’t implicitly equal 0 , 1 , 2  and 3 . Instead, the different enumeration cases are values in their own right, with an explicitly defined type of CompassPoint .

Other Topics

  • Raw Values.

  • Recursive Enumerations.